<template>
  <div class="app-container child-friendly relative min-h-screen overflow-hidden">
    <!-- 动画背景 -->
    <div class="animated-background absolute top-0 left-0 w-full h-full animate-background-move z-[-1] opacity-20">
<!--      <img src="../../../../public/backgpicture.jpg" alt="可爱背景图" class="background-img w-full h-full object-cover">-->
    </div>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" inline v-show="showSearch" label-width="68px"
             class="p-4 bg-white bg-opacity-80 rounded-md shadow-md">
      <el-form-item label="量表名称" prop="scaleName">
        <el-input
          v-model="queryParams.scaleName"
          placeholder="请输入量表名称"
          clearable
          @keyup.enter.native="handleQuery"
          class="child-friendly-input rounded-md shadow-sm bg-yellow-100"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                   class="child-friendly-button rounded-md shadow-sm bg-blue-500 hover:bg-blue-600 text-white">
          <i class="fas fa-star mr-2"></i>
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                   class="child-friendly-button rounded-md shadow-sm bg-green-500 hover:bg-green-600 text-white">
          <i class="fas fa-butterfly mr-2"></i>
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <div class="flex flex-wrap gap-2 p-4">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAssign"
        v-hasPermi="['dcp:scale:assign']"
        class="child-friendly-button rounded-md shadow-sm bg-purple-500 hover:bg-purple-600 text-white">
        <i class="fas fa-tasks mr-2"></i>
        分配
      </el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </div>
    <!-- 量表表格 -->
    <!--    <el-table v-loading="loading" :data="scaleList" @selection-change="handleSelectionChange"-->
    <!--              class="child-friendly-table rounded-md overflow-hidden shadow-md bg-white bg-opacity-80">-->
    <!--      <el-table-column type="selection" width="55" align="center"/>-->
    <!--      <el-table-column label="主键" align="center" prop="scaleId"/>-->
    <!--      <el-table-column label="量表名称" align="center" prop="scaleName"/>-->
    <!--      <el-table-column label="年级" align="center" prop="grade" width="120" />-->
    <!--      <el-table-column label="住院号" align="center" prop="admissionNumber" width="180" />-->
    <!--      <el-table-column label="就诊卡号" align="center" prop="cardNumber" width="180" />-->
    <!--      <el-table-column label="民族" align="center" prop="ethnicity" width="120" />-->
    <!--      <el-table-column label="父亲职业" align="center" prop="fatherOccupation" min-width="160" />-->
    <!--      <el-table-column label="母亲职业" align="center" prop="motherOccupation" min-width="160" />-->
    <!--      <el-table-column label="门诊号" align="center" prop="patientNumber" width="180" />-->
    <!--      <el-table-column label="联系方式" align="center" prop="phonenumber" width="200" />-->
    <!--      <el-table-column label="家庭住址" align="center" prop="address" min-width="240" show-overflow-tooltip />-->
    <!--      <el-table-column label="备注" align="center" prop="remark" min-width="200" show-overflow-tooltip />-->
    <!--    </el-table>-->
    <el-table v-loading="loading" :data="scaleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="scaleId" />
      <el-table-column label="量表名称" align="center" prop="scaleName" />
      <el-table-column label="等级" align="center" prop="level" />
      <el-table-column label="状态" align="center" key="remark" >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.remark" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="getToScaleDetail"
            v-hasPermi="['dcp:scale:edit']"
          >查看</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['dcp:scale:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="p-4 mt-0"
      style="margin-top: 0px"
    />
    <el-dialog
      :title="'分配选中的' + selectedRows.length + '条数据'"
      :visible.sync="assignDialogVisible"
      width="85%"
      max-width="1400px"
      append-to-body
      class="child-friendly-dialog custom-dialog"
      :before-close="handleBeforeClose"
    >
      <template #title>
        <div class="dialog-title flex items-center gap-2">
          <i class="fas fa-share-alt text-2xl text-purple-600"></i>
          <span class="font-bold text-lg">{{ '分配选中的' + selectedRows.length + '条数据' }}</span>
        </div>
      </template>
      <div class="p-6">
        <p class="text-gray-600 mb-4">
          以下是您选中的患者数据，可勾选后进行分配操作：
        </p>
        <el-table
          :data="patientList"
          stripe
          border
          class="child-friendly-table mt-4"
          style="width: 100%; max-height: 500px; overflow-y: auto"
          @selection-change="handleChildSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键" align="center" prop="patientId" />
          <el-table-column label="病患名称" align="center" prop="childName" />
          <el-table-column label="性别" align="center" prop="gender" />
          <el-table-column label="生日" align="center" prop="birth" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.birth, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="年级" align="center" prop="grade" />
          <el-table-column label="住院号" align="center" prop="admissionNumber" />
          <el-table-column label="就诊卡号" align="center" prop="cardNumber" />
          <el-table-column label="民族" align="center" prop="ethnicity" />
          <el-table-column label="父亲职业" align="center" prop="fatherOccupation" />
          <el-table-column label="母亲职业" align="center" prop="motherOccupation" />
          <el-table-column label="门诊号" align="center" prop="patientNumber" />
          <el-table-column label="联系方式" align="center" prop="phonenumber" />
          <el-table-column label="家庭住址" align="center" prop="address" />
          <el-table-column label="备注" align="center" prop="remark" />
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--          <el-table-column label="主键" align="center" prop="scaleId"/>-->
<!--          <el-table-column label="量表名称" align="center" prop="scaleName"/>-->
<!--          <el-table-column label="年级" align="center" prop="grade" width="120" />-->
<!--          <el-table-column label="住院号" align="center" prop="admissionNumber" width="180" />-->
<!--          <el-table-column label="就诊卡号" align="center" prop="cardNumber" width="180" />-->
<!--          <el-table-column label="民族" align="center" prop="ethnicity" width="120" />-->
<!--          <el-table-column label="父亲职业" align="center" prop="fatherOccupation" min-width="160" />-->
<!--          <el-table-column label="母亲职业" align="center" prop="motherOccupation" min-width="160" />-->
<!--          <el-table-column label="门诊号" align="center" prop="patientNumber" width="180" />-->
<!--          <el-table-column label="联系方式" align="center" prop="phonenumber" width="200" />-->
<!--          <el-table-column label="家庭住址" align="center" prop="address" min-width="240" show-overflow-tooltip />-->
<!--          <el-table-column label="备注" align="center" prop="remark" min-width="200" show-overflow-tooltip />-->
        </el-table>
        <pagination
          v-show="childtotal>0"
          :total="childtotal"
          :page.sync="childParams.pageNum"
          :limit.sync="childParams.pageSize"
          @pagination="getChildList"
        />
        <div class="mt-6 flex justify-end gap-4">
          <el-button
            type="primary"
            size="small"
            class="child-friendly-button bg-purple-600 hover:bg-purple-700"
            @click="handleAssignConfirm"
          >
            <i class="fas fa-check mr-2"></i> 确认分配（{{ assignedRows.length }}条）
          </el-button>
          <el-button
            size="small"
            class="child-friendly-button bg-gray-500 hover:bg-gray-600"
            @click="assignDialogVisible = false"
          >
            <i class="fas fa-times mr-2"></i> 取消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScale, getScale, delScale, addScale, updateScale } from "@/api/dcp/scale";
import { addAssign } from "@/api/dcp/screen"
import { listPatient} from "@/api/dcp/patient";
import {changeScale} from "@/api/dcp/scale";
import {changeUserStatus} from "@/api/system/user";
export default {
  name: "Scale",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 主表格选中数组
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      childtotal:0,
      scaleList: [],
      // 病患管理表格数据
      patientList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scaleName: null,
        grade: null,
        admissionNumber: null,
        cardNumber: null,
        ethnicity: null,
        fatherOccupation: null,
        motherOccupation: null,
        patientNumber: null,
        phonenumber: null,
        address: null,
        remark: null
      },
      childParams: {
        pageNum: 1,
        pageSize: 10,
        childName: null,
        gender: null,
        birth: null,
        grade: null,
        admissionNumber: null,
        cardNumber: null,
        ethnicity: null,
        fatherOccupation: null,
        motherOccupation: null,
        patientNumber: null,
        phonenumber: null,
        address: null,
      },
      form: {},
      rules: {},
      // 分配对话框相关
      selectedRows: [], // 主表格选中的行
      selectPatientRow:[],
      assignDialogVisible: false,
      assignedRows: [], // 分配对话框中勾选的行
      patientRows:[]
    };
  },
  created() {
    this.getList();
    this.getChildList()
  },
  methods: {
    /** 查询量表管理列表 */
    getList() {
      this.loading = true;
      listScale(this.queryParams).then(response => {
        this.scaleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询病患管理列表 */
    getChildList() {
      this.loading = true;
      listPatient(this.childParams).then(response => {
        this.patientList = response.rows;
        this.childtotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scaleId: null,
        scaleName: null,
        grade: null,
        admissionNumber: null,
        cardNumber: null,
        ethnicity: null,
        fatherOccupation: null,
        motherOccupation: null,
        patientNumber: null,
        phonenumber: null,
        address: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 用户状态修改
    handleStatusChange(row) {
      let text = row.remark === "0" ?"启用":"停用" ;
      this.$modal.confirm('确认要"' + text + '""' + row.scaleName + '"量表吗？').then(function() {
        return changeScale(row.scaleId, row.remark);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.remark= row.remark === "0" ? "1" : "0";
      });
    },
    // 主表格选中事件
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      console.log(this.selectedRows)
      this.ids = selection.map(item => item.scaleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // // 分配对话框选中事件
    // handleAssignSelectionChange(selection) {
    //   this.assignedRows = selection; // 实时更新分配对话框中的勾选数据
    //   console.log(this.selectedRows)
    // },
    handleChildSelectionChange(selection){
      this.patientRows = selection;
      console.log(this.patientRows)
    },
    /** 分配按钮操作 */
    handleAssign() {
      if (this.selectedRows.length === 0) {
        return this.$message.warning("请选择需要分配的量表");
      }
      this.assignDialogVisible = true;
      // 初始化分配对话框的勾选状态（可选：默认全选或清空）
      this.assignedRows = [...this.selectedRows]; // 可选：默认全选
    },
    // 确认分配逻辑
    handleAssignConfirm() {
      if (this.assignedRows.length === 0) {
        return this.$message.warning("请至少勾选一条数据进行分配");
      }

      // 示例：校验联系方式格式
      // const phoneReg = /^1[3-9]\d{9}$/;
      // const hasInvalidPhone = this.assignedRows.some(row => !phoneReg.test(row.phonenumber));
      // if (hasInvalidPhone) {
      //   return this.$message.warning("请检查联系方式格式是否正确");
      // }

      // 模拟分配过程（需替换为真实API）
      // const loading = this.$loading({
      //   lock: true,
      //   text: "分配中...",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.2)"
      // });
      var scaleIds = []
      var patientIds = []
      for (let i = 0; i < this.selectedRows.length; i++) {
        let sId = this.selectedRows[i].scaleId
        scaleIds[i] = sId
      }
      for (let i = 0; i < this.patientRows.length; i++) {
        let pId = this.patientRows[i].patientId
        patientIds[i] = pId
      }
      console.log(scaleIds)
      console.log(patientIds)
      /*addAssign(scaleIds,patientIds).then(res=>{
        console.log(res.data)
        this.selectedRows = []
        this.patientRows = []
      })*/
      addAssign(scaleIds,patientIds).then(res=>{
        console.log(res.data)
        const loading = this.$loading({
          lock: true,
          text: "分配中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.2)"
        });
        setTimeout(() => {
          loading.close();
          // ${this.assignedRows.length} 条
          this.$message.success(`成功分配数据！`);
          this.assignDialogVisible = false;
          this.assignedRows = []; // 清空已选数据
          this.getList(); // 刷新主表格
        }, 1500);
      })
    },
    handleBeforeClose(){
    this.assignDialogVisible = false
    },
    getToScaleDetail(){
      console.log(66)
    }
    // 其他方法（新增、修改、删除等）保持不变...
    // （为节省篇幅，省略重复的CRUD方法代码，可根据实际项目补充完整）
  }
};
</script>

<style scoped>
.child-friendly {
  /*font-family: 'Comic Sans MS', cursive, sans-serif;*/
}

.animated-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  animation: background-move 10s linear infinite;
  z-index: -1;
  opacity: 0.2;
}

@keyframes background-move {
  from { background-position: 0 0; }
  to { background-position: -100% 0; }
}

.child-friendly-input {
  border-radius: 0.25rem;
  box-shadow: 0 0 0.3125rem #ccc;
  background-color: #f9f3d8;
}

.child-friendly-button {
  border-radius: 0.25rem;
  box-shadow: 0 0 0.3125rem #ccc;
  padding: 0.3125rem 0.625rem;
  border: none;
}

.child-friendly-table {
  border-radius: 0.25rem;
  overflow: hidden;
  box-shadow: 0 0 0.625rem #ccc;
  --el-table-border-color: #e9ecef;
  margin-bottom: 0 !important; /* 确保表格底部无间距 */
}

.child-friendly-table .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

.child-friendly-dialog {
  border-radius: 0.25rem;
  box-shadow: 0 0 0.9375rem #ccc;
  --el-dialog-bg-color: transparent;
}

.custom-dialog {
  --el-dialog-padding: 0;
  border-radius: 50px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  background: rgba(255, 255, 255, 0);
  max-width: 1700px;
  --el-dialog-bg-color: transparent;
}

.custom-dialog .el-dialog__header {
  padding: 24px 32px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);

}

.custom-dialog .el-dialog__title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
}

.custom-dialog .el-dialog__body {
  padding: 32px;
}

.bg-green-200 {
  background-color: #ebf9eb !important;
}

.bg-yellow-200 {
  background-color: #fff3cd !important;
}

.bg-red-200 {
  background-color: #ffe6e6 !important;
}

.el-table .el-table__cell[prop="address"],
.el-table .el-table__cell[prop="remark"] {
  padding: 8px 12px;
  white-space: normal;
  line-height: 1.5;
}

/* 透明遮罩层 */
.v-modal {
  background-color: transparent !important;
}

/*!* 确保分页顶部无间距 *!*/
/*.pagination {*/
/*  margin-top: 0 !important;*/
/*}*/
</style>
